package com.ultrasoft.farmasoft.web;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.service.GeneralAdministrationService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;
import com.ultrasoft.farmasoft.util.UtilUseFulTree;
import com.ultrasoft.farmasoft.domain.Country;
import com.ultrasoft.farmasoft.domain.Region;
import com.ultrasoft.farmasoft.domain.Locality;
import com.ultrasoft.farmasoft.domain.LocalityPK;

@Controller
@SessionAttributes({"s_UserPharmacy"})
@RequestMapping(value="/GeneralAdministration")
public class AdminGeneralController {
	
	private final GeneralAdministrationService generalAdminService;
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;

	@Autowired
    public AdminGeneralController(GeneralAdministrationService generalAdminService) {
        this.generalAdminService = generalAdminService;
    }
	
	//start esencial
	private String redirectHumanResources(HttpServletRequest request){
		return "redirect:/configActivePrinciple?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}
	
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	
	private String handleRedirectHumanResources(HttpServletRequest request,String headMainList) {
    	try {
    		return "redirect:/"+headMainList+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
		}catch (Exception e) {
			return redirectHumanResources(request);
		}
    }
	//Control main page ADMINGENERAL
	@RequestMapping(value="/adminGeneral", method = RequestMethod.GET)	
	public String handleFront1(SessionStatus status,HttpServletRequest request, Model model)throws ServletException  {
		if(this.sessionControl(request)){
			return UtilCommon.fAdministrationGeneral+"adminGeneral";
	    }
		else 
			return redirectHumanResources(request);
	}			
	
	/* Add sub-menu the Administration General COUNTRY*/
	@RequestMapping(value="/adminCountry", method=RequestMethod.GET)
	public String handleRequestAdminHumanResources(SessionStatus status,HttpServletRequest request, Model model)throws ServletException  {
		if(this.sessionControl(request)){
			List<Country> contries = generalAdminService.getCountryList();
			model.addAttribute("contries",contries);
			return UtilCommon.fCountry+"adminCountry";
	    }
		else 
			return redirectHumanResources(request);
	}
	
	/*
	 * COUNTRY
	 */
	// Method add and edit adminCountry
	 @RequestMapping(value = "/generalAdministrationAddEditCountry", method = RequestMethod.POST)
	 public @ResponseBody String handleRequestGeneralAdministrationAddEditCountry(@RequestParam short idCountry,@RequestParam Integer accion,@RequestParam String name,@RequestParam String sigla){
	    String msg="";
		if(accion == 0){
			msg="Se agrego ";
			generalAdminService.addCountry(new Country(idCountry, name, sigla));
		}
		if(accion == 1){
		    msg="Se Edito ";
		    Country c=generalAdminService.searchCountryByID(idCountry);
		    c.setName(name);
		    c.setInitials(sigla);
		    generalAdminService.updateCountry(c);
		}
		return msg+"correctamente!!!";
	}
	//remove country
	 @RequestMapping(value = "/generalAdministrationRemoveCountry", method = RequestMethod.GET)
	 public @ResponseBody String handleGeneralAdministrationRemoveCountry(@RequestParam short idCountry,@RequestParam String name, HttpServletRequest request){
		 //System.out.println(request.getParameterMap());
		 generalAdminService.removeCountry(generalAdminService.searchCountryByID(idCountry));
		 return "El Pais "+name+" se Elimino correctamente!!!";
	 }
	
	 
	/*
	 * REGION
	*/ 
	/* Add submenu the Administration General REGION*/
	@RequestMapping(value="/adminRegion", method=RequestMethod.GET)
	public String handleRequestGeneralAdministrationAdminRegion(SessionStatus status,HttpServletRequest request, Model model)throws ServletException {
		if(this.sessionControl(request)){
			List<Region> regiones = generalAdminService.getRegionList();
			model.addAttribute("regiones",regiones);
			List<Country> count = generalAdminService.getCountryList();
			model.addAttribute("countryListWithId",count);
			
			return UtilCommon.fRegion+"adminRegion";			
		}else
			return redirectHumanResources(request);
    }
	// edit and add Region
	@RequestMapping(value = "/generalAdministrationAddEditRegion", method = RequestMethod.POST)
	public @ResponseBody short handleRequestGeneralAdministrationAddEditRegion(@RequestParam String nombre,@RequestParam short idPais,@RequestParam String sigla,@RequestParam Integer idRegion, @RequestParam Integer accion ,Model model, HttpServletRequest request){
		String msg="";
		if(accion == 0){
			msg="Se agrego ";
			Country co=generalAdminService.searchCountryByID(idPais);
			generalAdminService.addRegion(new Region(idRegion,co,nombre,sigla));
	    }
	    if(accion == 1){
	    	 msg="Se Edito ";
	    	 Region r=generalAdminService.searchRegionByRegionId(idRegion);
	    	 r.setName(nombre);
	    	 r.setInitials(sigla);
	    	 Country co=generalAdminService.searchCountryByID(idPais); // edit country Id
	    	 r.setCountryId(co);
			 generalAdminService.updateRegion(r);
	    }
	   	return idPais;
	}
	
	// remove Region
	@RequestMapping(value = "/generalAdministrationRemoveRegion", method = RequestMethod.GET)
   	public @ResponseBody String handleRequestGeneralAdministrationRemoveRegion(@RequestParam Integer regionId,@RequestParam short countryId,@RequestParam String name,HttpServletRequest request){
		generalAdminService.removeRegion(generalAdminService.searchRegionByRegionId(regionId));
		return "El Pais "+name+" se Elimino correctamente!!!";
    }
    @RequestMapping(value = "/generalAdministrationSelectCountry", method = RequestMethod.GET)
   	public @ResponseBody short handleRequestGeneralAdministrationSelectCountry(@RequestParam short idCountry,@RequestParam String name){
        return idCountry;
    }
    /*
	 * LOCALITY
	 */
	/* Add submenu the Administration General LOCALITY */
	@RequestMapping(value="/adminLocality", method=RequestMethod.GET)
	public String handleRequestGeneralAdministrationAdminLocality(SessionStatus status,HttpServletRequest request, Model model)throws ServletException {
		if(this.sessionControl(request)){
			List<Locality> localidades = generalAdminService.getLocality();
			model.addAttribute("localidades",localidades);
			List<Country> paices= generalAdminService.getCountryList();
			model.addAttribute("paices",paices);
			
			List<Region> ciudades=generalAdminService.getRegionList();
			model.addAttribute("ciudades", ciudades);
			return UtilCommon.fLocality+"adminLocality";
		}else
			return redirectHumanResources(request);
    }
	
	@RequestMapping(value = "/AjaxAdministrationAdminLocality", method = RequestMethod.GET)
   	public @ResponseBody String handleRequestAjaxAdministrationAdminLocality(@RequestParam short idCountry)throws JsonIOException{

		List<Region> regionList = generalAdminService.getRegionList(idCountry);
		JsonArray groupArray = new JsonArray();
        if(!regionList.isEmpty()){
			for (Region r : regionList) {
		        JsonObject groupJSON = new JsonObject();
	            groupJSON.addProperty("regionId",r.getRegionId());
	            groupJSON.addProperty("name",r.getName());
	            groupArray.add(groupJSON);
	        }
		}else{
	        JsonObject groupJSON = new JsonObject();
	        groupJSON.addProperty("name","");
	        groupArray.add(groupJSON);
		}
    	return groupArray.toString();
    }
	
	
	//edit and add Locality
	@RequestMapping(value = "/AjaxAdministrationAdminLocalityNewEdit",method = RequestMethod.POST)
   	public @ResponseBody String handleRequestAjaxAcademicAdminBooksShowTableByStudyPlanNewEdit(@RequestParam String nombre,@RequestParam String sigla,@RequestParam String zona ,@RequestParam Integer accion, HttpServletRequest request){
		//System.out.println(request.getParameterMap()); 
		String msg="";
		
    	if(accion == 0){
    		//int myint = (int)(myshort)  para convertir de un short a un int  biseversa  = (short) (myint)
    		short idLocal=generalAdminService.getLocalityIdMax(UtilConverter.converterStringToInteger(request, "idRegion")); //regained idLocalityMax
    		generalAdminService.addLocality(new Locality( UtilConverter.converterStringToInteger(request, "idRegion"), idLocal,nombre,sigla,zona,true));
    		msg="Se agrego "+idLocal;
    	}
    	if(accion == 1){
    		msg="Se Edito ";
    		Locality lo=generalAdminService.searchLocalityByRegionIdByLocalityId(UtilConverter.converterStringToInteger(request, "iddRegion"), UtilConverter.converterStringToShort(request, "iddLocalidad"));
    		lo.setName(nombre);
    		lo.setInitials(sigla);
    		lo.setArea(zona);
    		generalAdminService.updateLocality(lo);
       	}
		return msg;
    }
	
	//Delete locality
	@RequestMapping(value = "/generalAdministrationRemoveLocality", method = RequestMethod.GET)
   	public @ResponseBody String handleRequestGeneralAdministrationRemoveLocality(@RequestParam int regionId, @RequestParam short localityId, @RequestParam String name, HttpServletRequest request){
        Locality localidad=generalAdminService.searchLocalityByRegionIdByLocalityId(regionId, localityId);
        
		generalAdminService.removeLocality(localidad);
		return "La Localidad "+name+" se Elimino correctamente!!!";
	}	
}

